#!/usr/bin/python3
# -*- coding: UTF-8 -*- 
"""
output funclist in YOUR_APP.s
    objdump -d YOUR_APP > YOUR_APP.s
    python3 output_fun_sort.py -i YOUR_APP.s -l c/c++
"""

import re
import os
import stat
import argparse

def get_func_list(args):
    """
    get a list of funcs from input_file
    """
    lang=args.language
    input_file=args.input_file
    print("lang: {}".format(lang))
    print("input_file: {}".format(input_file))

    with open(input_file,"r") as file:
        func_record=0
        call_record=0
        for line in file.readlines():
            line=line.strip()
            caller=None
            if "adrp" in line:
                continue
            if re.match(r'Disassembly of section \.text',line):
                call_record=1
                continue
            if re.match(r'Disassembly of section',line) and call_record==1:
                break

            if call_record==1:
                if lang=="C" or lang=="c":
                    result=re.match(r'^([0-9a-f]+)\s+<(\w+)(\.\w+\.\d)?>:$',line)
                elif lang=="C++" or lang=="c++":
                    result=re.match(r'^([0-9a-f]+)\s+<(.*\((.*)\))(\sconst|(\s\['r'.*\])*)?>:$',line)
                else:
                    print("error: please input for language as args!")
                    return None

                if result is not None:
                    caller=result.group(2)

                    if lang=="C++" or lang=="c++":
                        if result.group(4) is not None and result.group(4).strip()=="const":
                            caller='{}{}'.format(caller,result.group(4))

                if re.match(r'\s*$',line):
                    func_record=0

                # if func_record==1:
                #     if lang=="C" or lang=="c":
                #         res=re.match(r'<(\w+)(\.\w+\.\d)?>:$',line)
                #     elif lang=="C++" or lang=="c++":
                #         result=re.match(r'<(.*\((.*)\))(\sconst|(\s\[.*\])*)?>$',line)
                #     else:
                #         print("error: please input for language as args!")
                #         return None
                if caller is not None:
                    print("func: {}".format(caller))
        return None

def defin_and_parse_args():
    parser=argparse.ArgumentParser(description="func tool for asm")
    parser.add_argument('-l','--language',type=str,help='language for asm',required=True)
    parser.add_argument('-i','--input_file',type=str,help='input file witch asm need to be parsed',required=True)

    return parser.parse_args()

def main():
    args=defin_and_parse_args()
    get_func_list(args)

if __name__=='__main__':
    main()



                
        
